package org.spring.boot.redis;

import java.util.concurrent.TimeUnit;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.dao.DataAccessException;
import org.springframework.data.redis.connection.RedisConnection;
import org.springframework.data.redis.core.RedisCallback;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.data.redis.core.ValueOperations;
import org.springframework.stereotype.Component;

@Component
public class SampleRedisService {

	@Autowired
	private StringRedisTemplate stringRedisTemplate;
	
	public void set(String k, String v){
		ValueOperations<String, String> ops = this.stringRedisTemplate.opsForValue();
		ops.set(k, v);
	}
	
	public void set(String k, String v, long timeOut){
		ValueOperations<String, String> ops = this.stringRedisTemplate.opsForValue();
		ops.set(k, v, timeOut, TimeUnit.MILLISECONDS);
		this.stringRedisTemplate.expire(k, timeOut, TimeUnit.MILLISECONDS);
	}
	
	public String get(String k){
		ValueOperations<String, String> ops = this.stringRedisTemplate.opsForValue();
		return ops.get(k);
	}
	
	public void lpush(final String k, final String v){
		this.stringRedisTemplate.execute(new RedisCallback<Boolean>() {
			public Boolean doInRedis(RedisConnection arg0)
					throws DataAccessException {
				arg0.lPush(k.getBytes(), v.getBytes());
				return null;
			}
		});
	}
	
	public String rpop(final String k){
		return this.stringRedisTemplate.execute(new RedisCallback<String>() {
			public String doInRedis(RedisConnection paramRedisConnection)
					throws DataAccessException {
				return new String(paramRedisConnection.rPop(k.getBytes()));
			}
		});
	}
}
